import { _decorator, Component, Node, ProgressBar, Label, director, resources, Asset, assetManager } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LoadingManager')
export class LoadingManager extends Component {
    @property(ProgressBar)
    progressBar: ProgressBar = null!;

    @property(Label)
    progressLabel: Label = null!;

    private _totalCount: number = 0;
    private _currentCount: number = 0;
    private _isLoading: boolean = false;

    start() {
        // 初始化进度条
        this.progressBar.progress = 0;
        this.progressLabel.string = '0%';
        this.startLoading();
    }

    startLoading() {
        if (this._isLoading) return;
        this._isLoading = true;

        // 创建加载任务列表
        const loadTasks: Promise<void>[] = [];
        
        // 加载场景资源
        loadTasks.push(this.loadSceneAssets());
        
        // 如果有其他类型的资源也可以在这里添加
        // loadTasks.push(this.loadAudioAssets());
        // loadTasks.push(this.loadTextureAssets());

        // 执行所有加载任务
        Promise.all(loadTasks)
            .then(() => {
                this.loadingComplete();
            })
            .catch(err => {
                console.error('Load assets error:', err);
            });
    }

    private async loadSceneAssets(): Promise<void> {
        return new Promise((resolve, reject) => {
            // 预加载下一个场景
            director.preloadScene("game", 
                (completedCount: number, totalCount: number) => {
                    if (totalCount <= 0) return;
                    const progress = completedCount / totalCount;
                    this.updateProgress(progress);
                },
                (error: Error) => {
                    if (error) {
                        console.error('Preload scene error:', error);
                        reject(error);
                        return;
                    }
                    resolve();
                }
            );
        });
    }

    updateProgress(progress: number) {
        // 更新进度条和文本
        this.progressBar.progress = progress;
        this.progressLabel.string = Math.floor(progress * 100) + '%';
        console.log('Loading progress:', progress);
    }

    loadingComplete() {
        this._isLoading = false;
        console.log('All resources loaded!');
        // 加载完成后切换到游戏场景
        director.loadScene("game");
    }
} 